package fr.dauphine.bookstore.frontoffice;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import fr.dauphine.bookstore.hibernate.HibernateUtil;
import fr.dauphine.bookstore.modele.Order;
import fr.dauphine.bookstore.modele.User;

/**
 * Sauvegarde de la commande.
 */
public final class SaveOrderServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = -3035842828604005374L;

	/**
	 * Traite la methode POST.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {

		Order order = SessionUtil.getOrder(request.getSession());
		User user = SessionUtil.getUser(request.getSession());

		order.setUser(user);
		order.setOrderDate(Calendar.getInstance().getTime());

		Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
		hSession.save(order);

		SessionUtil.removeOrder(request.getSession());
		response.sendRedirect("orders.jsp");
	}
}
